package com.carl.servlet;

import com.carl.annotation.MyController;
import com.carl.annotation.MyRequestMapping;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyDispatcherServlet extends HttpServlet{

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<String>();

    private Map<String, Object> ioc = new HashMap<String, Object>();

    private Map<String, Method> handlerMapping = new HashMap<String, Method>();

    private Map<String, Object> controllerMap = new HashMap<String, Object>();

    private String web_init_parameter_location = "contextConfigLocation";

    private String resource_parameter_scan = "scanPackage";

    @Override
    public void init(ServletConfig config)throws ServletException {
        String location = config.getInitParameter(web_init_parameter_location);
        // 加载配置文件
        this.doLoadConfig(location);
        // 初始化所有相互关联的类似，并扫描指定包下的所有类
        String packageName = properties.getProperty(resource_parameter_scan);
        this.doScanner(packageName);
        // 得到类，随后通过反射机制，实例化，放置到ioc容器中(k,v) beanName默认小写字母
        this.doInstance();
        // 初始化 handlerMapper (url与method一一对应)
        this.initHandlerMapper();

    }

    private void  doLoadConfig(String location){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(location);
        try {
            if (resourceAsStream != null) {
                properties.load(resourceAsStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (resourceAsStream != null) {
                try {
                    resourceAsStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doScanner(String packageName){
//        URL url = this.getClass().getClassLoader().getResource("/" + packageName.replace("\\.", "/"));
        URL url = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.", "/"));
        File directory = new File(url.getFile());
        for (File file : directory.listFiles()) {
            if (file.isDirectory() == true) {
                this.doScanner(packageName + "." + file.getName());
            } else {
                String className = packageName + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }

    private void doInstance(){
        if (classNames.isEmpty()) {
            return;
        }
        for (String classname : classNames) {
            try {
                Class<?> clazz = Class.forName(classname);
                if (clazz.isAnnotationPresent(MyController.class)) {
                    ioc.put(this.toLowerFirstWord(clazz.getSimpleName()), clazz.newInstance());
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    private String toLowerFirstWord(String name){
        char[] charArray = name.toCharArray();
        charArray[0] += 32;
        return String.valueOf(charArray);
    }

    private void initHandlerMapper(){
        if (ioc.isEmpty()) {
            return;
        }
        try {
            for (Entry<String, Object> entry : ioc.entrySet()) {
                Class<? extends Object> clazz = entry.getValue().getClass();
                if (clazz.isAnnotationPresent(MyController.class) == false) {
                    continue;
                }
                String baseUrl = "";
                if (clazz.isAnnotationPresent(MyRequestMapping.class)) {
                    MyRequestMapping annotation = clazz.getAnnotation(MyRequestMapping.class);
                    baseUrl = annotation.value();
                }
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(MyRequestMapping.class) == false) {
                        continue;
                    }
                    MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                    String url = annotation.value();
                    url = (baseUrl + "/" + url).replaceAll("/+", "/");
                    handlerMapping.put(url, method);
                    controllerMap.put(url,clazz.newInstance());
                    System.out.println(url + " <===> " + method);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    @Override
    protected void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException{
        try {
            this.doDispatch(request, response);
        } catch (Exception e) {
            response.getWriter().write("500!! Server Exception");
        }
    }

    private void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (handlerMapping.isEmpty()) {
            return;
        }

        String url = request.getRequestURI();

        String contextPath = request.getContextPath();

        url = url.replace(contextPath, "").replace("/+", "/");

        if (this.handlerMapping.containsKey(url) == false) {
            response.getWriter().write("$$ 404 not found ! ##");
        }

        Method method = this.handlerMapping.get(url);

        Class<?>[] parameterTypes = method.getParameterTypes(); // 获取方法的参数列表

        Map<String, String[]> parameterMap = request.getParameterMap(); // 获取请求参数

        Object[] paramValues = new Object[ parameterTypes.length ]; // 保存参数值

        for (int i = 0 ; i < parameterTypes.length ; i++) {
            String requestParam = parameterTypes[ i ].getSimpleName();
            if (requestParam.equals("HttpServletRequest")) {
                paramValues[ i ] = request;
                continue;
            }
            if (requestParam.equals("HttpServletResponse")) {
                paramValues[ i ] = response;
                continue;
            }
            if (requestParam.equals("String")) {
                for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
                    String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
                    paramValues[ i ] = value;
                }
            }
        }

        try {
            method.invoke(this.controllerMap.get(url), paramValues);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
